import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

/// 🔐 认证服务
/// 
/// 功能:
/// - 发送验证码
/// - 登录/注册
/// - Token管理
/// - 用户信息存储
class AuthService {
  static const String _tokenKey = 'auth_token';
  static const String _userIdKey = 'user_id';
  static const String _phoneKey = 'phone_number';
  static const String _usernameKey = 'username';

  final String serverUrl;

  AuthService(this.serverUrl);

  /// 发送验证码
  /// 
  /// [phoneNumber] 手机号（11位）
  /// 
  /// 返回: (success, verificationId, message)
  Future<(bool, String?, String)> sendCode(String phoneNumber) async {
    try {
      if (phoneNumber.length != 11) {
        return (false, null, '请输入11位手机号');
      }

      final response = await http.post(
        Uri.parse('$serverUrl/api/auth/send-code'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'phone_number': phoneNumber}),
      );

      final data = jsonDecode(response.body);

      if (response.statusCode == 200 && data['success'] == true) {
        final verificationId = data['data']['verification_id'] as String?;
        return (true, verificationId, '验证码已发送');
      } else {
        final message = data['message']?.toString() ?? '发送失败';
        return (false, null as String?, message);
      }
    } catch (e) {
      return (false, null, '网络错误: $e');
    }
  }

  /// 登录/注册
  /// 
  /// [phoneNumber] 手机号
  /// [code] 验证码
  /// [verificationId] 验证ID（从sendCode获取）
  /// 
  /// 返回: (success, userId, message)
  Future<(bool, String?, String)> login({
    required String phoneNumber,
    required String code,
    required String verificationId,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$serverUrl/api/auth/verify-code'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'phone_number': phoneNumber,
          'code': code,
          'verification_id': verificationId,
        }),
      );

      final data = jsonDecode(response.body);

      if (response.statusCode == 200 && data['success'] == true) {
        final token = data['data']['token'] as String;
        final user = data['data']['user'];
        final userId = user['id'].toString();
        final username = user['username'] as String;

        // 保存认证信息
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString(_tokenKey, token);
        await prefs.setString(_userIdKey, userId);
        await prefs.setString(_phoneKey, phoneNumber);
        await prefs.setString(_usernameKey, username);

        return (true, userId, '登录成功');
      } else {
        final message = data['message']?.toString() ?? '登录失败';
        return (false, null as String?, message);
      }
    } catch (e) {
      return (false, null, '网络错误: $e');
    }
  }

  /// 获取Token
  Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }

  /// 获取UserID
  Future<String?> getUserId() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_userIdKey);
  }

  /// 获取手机号
  Future<String?> getPhoneNumber() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_phoneKey);
  }

  /// 获取用户名
  Future<String?> getUsername() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_usernameKey);
  }

  /// 检查是否已登录
  Future<bool> isLoggedIn() async {
    final token = await getToken();
    return token != null && token.isNotEmpty;
  }

  /// 登出
  Future<void> logout() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
    await prefs.remove(_userIdKey);
    await prefs.remove(_phoneKey);
    await prefs.remove(_usernameKey);
  }

  /// 获取认证头（用于HTTP请求）
  Future<Map<String, String>> getAuthHeaders() async {
    final token = await getToken();
    if (token == null || token.isEmpty) {
      return {};
    }
    return {'Authorization': 'Bearer $token'};
  }

  /// 验证Token是否仍然有效（通过访问API）
  Future<bool> validateToken() async {
    try {
      final token = await getToken();
      if (token == null || token.isEmpty) {
        return false;
      }

      final response = await http.get(
        Uri.parse('$serverUrl/api/tunnels'),
        headers: {'Authorization': 'Bearer $token'},
      );

      return response.statusCode == 200;
    } catch (e) {
      return false;
    }
  }
}

